package com.gzxx.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gzxx.constant.ServiceCodeStatus;
import com.gzxx.constant.SystemConstant;
import com.gzxx.domain.converter.SysMenuConverter;
import com.gzxx.domain.dto.SysMenuDto;
import com.gzxx.domain.vo.SysMenuVo;
import com.gzxx.exception.ServiceException;
import com.gzxx.security.CurrentUser;
import com.gzxx.service.SysMenuService;
import com.gzxx.util.ServerResponse;
import com.gzxx.util.SysLoginUserHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author pengpdx
 * @Date 2020/7/24 10:01
 * 系统目录
 */
@Api(tags = "系统菜单相关接口")
@RestController
@RequestMapping("menus")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysMenuController {

    private final SysMenuService sysMenuService;

    /**
     * 新增 菜单
     *
     * @param sysMenuDto
     * @return
     */
    @ApiOperation("新增菜单")
    @PostMapping("/add")
    @PreAuthorize("@rbac.hasPermission('system:menus:add')")
    public ServerResponse add(@RequestBody SysMenuDto sysMenuDto) {
        this.verifyForm(sysMenuDto);
        boolean result = sysMenuService.add(SysMenuConverter.MAPPER.convert(sysMenuDto));
        return result ? ServerResponse.success(ServiceCodeStatus.SUCCESS) : ServerResponse.error();
    }

    /**
     * 删除
     *
     * @param params
     * @return
     */
    @ApiOperation("根据菜单id删除菜单")
    @PostMapping("/delete")
    @PreAuthorize("@rbac.hasPermission('system:menus:delete')")
    public ServerResponse delete(@RequestBody Map<String, Object> params) {
        Long id = Long.parseLong(params.get("id").toString());
        List<SysMenuVo> menuList = sysMenuService.queryListByParentId(id);
        if (CollectionUtils.isNotEmpty(menuList) && menuList.size() > 0) {
            return ServerResponse.error("请先删除子菜单或按钮");
        }
        boolean result = sysMenuService.delete(id);
        return result ? ServerResponse.success(ServiceCodeStatus.SUCCESS) : ServerResponse.error();
    }

    @ApiOperation("更新菜单")
    @PostMapping("/update")
    @PreAuthorize("@rbac.hasPermission('system:menus:update')")
    public ServerResponse update(@RequestBody SysMenuDto sysMenuDto) {
        this.verifyForm(sysMenuDto);
        boolean result = sysMenuService.update(SysMenuConverter.MAPPER.convert(sysMenuDto));
        return result ? ServerResponse.success(ServiceCodeStatus.SUCCESS) : ServerResponse.error();
    }

    /**
     * 根据ID获取目录
     *
     * @param id
     * @return
     */
    @ApiOperation("根据菜单id获取菜单明细")
    @GetMapping("/detail")
    @PreAuthorize("@rbac.hasPermission('system:menus:select')")
    public ServerResponse<SysMenuVo> detail(@RequestParam("id") Long id) {
        return ServerResponse.success(sysMenuService.getSysMenuById(id));
    }

    /**
     * 列表展示菜单信息
     *
     * @return
     */
    @ApiOperation("获取树形菜单列表")
    @PostMapping("/list")
    @PreAuthorize("@rbac.hasPermission('system:menus:list')")
    public ServerResponse<SysMenuVo> list() {
        List<SysMenuVo> list = sysMenuService.getAllSysMenuList(null);
        return ServerResponse.success(list);
    }

    /**
     * 获取用户导航栏菜单
     *
     * @return
     */
    @ApiOperation("获取用户导航栏菜单")
    @GetMapping("/nav")
    public ServerResponse nav() {
        CurrentUser currentUser = SysLoginUserHelper.getCurrentPrincipal();
        Map<String, Object> map = new HashMap<>();

        if (ObjectUtils.isNotEmpty(currentUser)) {
            List<SysMenuVo> menuList = sysMenuService.getUserMenuList(currentUser.getId());
            List<String> permissions = currentUser.getPermissions();

            map.put("menuList", menuList);
            map.put("permissions", permissions);
        }
        return ServerResponse.success(map);
    }

    /**
     * 列表展示菜单信息
     *
     * @return
     */
    @ApiOperation("获取目录菜单列表")
    @PostMapping("/listMenu")
    @PreAuthorize("@rbac.hasPermission('system:menus:list')")
    public ServerResponse<SysMenuVo> listMenu() {
        List<SysMenuVo> list = sysMenuService.getAllSysMenuList(SystemConstant.MenuType.BUTTON.getValue());
        return ServerResponse.success(list);
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuDto sysMenuDto) {

        if (StringUtils.isBlank(sysMenuDto.getMenuName())) {
            throw new ServiceException("菜单名称不能为空");
        }

        if (sysMenuDto.getParentId() == null) {
            throw new ServiceException("上级菜单不能为空");
        }

        //菜单
        if (sysMenuDto.getMenuType() == SystemConstant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(sysMenuDto.getUrl())) {
                throw new ServiceException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = SystemConstant.MenuType.CATALOG.getValue();
        if (sysMenuDto.getParentId() != 0) {
            SysMenuVo parentMenu = sysMenuService.getSysMenuById(sysMenuDto.getParentId());
            parentType = parentMenu.getMenuType();
        }

        //目录、菜单
        if (sysMenuDto.getMenuType() == SystemConstant.MenuType.CATALOG.getValue() ||
                sysMenuDto.getMenuType() == SystemConstant.MenuType.MENU.getValue()) {
            if (parentType != SystemConstant.MenuType.CATALOG.getValue()) {
                throw new ServiceException("上级菜单只能为目录类型");
            }
        }

        //按钮
        if (sysMenuDto.getMenuType() == SystemConstant.MenuType.BUTTON.getValue()) {
            if (parentType != SystemConstant.MenuType.MENU.getValue()) {
                throw new ServiceException("上级菜单只能为菜单类型");
            }
        }
    }
}
